import { setupServer } from "msw/node";
import { rest } from "msw";
import { http } from "../hooks/useHttp";

const apiURL = process.env.REACT_APP_API_URL;

const server = setupServer();
// beforeAll, afterEach, afterAll, test 等都是 jest 测试库提供的
// beforeAll 执行所有测试之前，先来执行某个回调函数
beforeAll(() => server.listen());
// afterEach 跑完每个测试后，都重置 mock 路由。
afterEach(() => server.resetHandlers());
// afterAll 所有测试跑完后，关闭 mock 路由
afterAll(() => server.close());

test("http 方法发送异步请求", async () => {
  const endpoint = "test-endpoint";
  const mockResult = { mockValue: "mock" };

  server.use(
    rest.get(`${apiURL}/${endpoint}`, async (req, res, ctx) => {
      return res(ctx.json(mockResult));
    })
  );
  const result = await http(endpoint);
  expect(result).toEqual(mockResult);
});

test("http 方法请求时自动携带 token", async () => {
  const token = "FAKE_TOKEN";
  let request: any;
  const endpoint = "test-endpoint";
  const mockResult = { mockValue: "mock" };

  server.use(
    rest.get(`${apiURL}/${endpoint}`, async (req, res, ctx) => {
      request = req;
      return res(ctx.json(mockResult));
    })
  );
  await http(endpoint, { token });
  expect(request.headers.get("Authorization")).toBe(`Bearer ${token}`);
});
